<template>
  <div class="login-container">
    <!-- 登录表单卡片 -->
    <div class="login-card">
      <div class="login-header">
        <div class="logo">
          <el-icon><ShoppingBag /></el-icon>
          <span class="logo-text">AI商城</span>
        </div>
        <h2 class="login-title">欢迎登录</h2>
        <p class="login-subtitle">请输入您的账号和密码</p>
      </div>
      
      <div class="login-form">
        <el-form 
          ref="loginFormRef" 
          :model="loginForm" 
          :rules="loginRules" 
          class="form"
        >
          <el-form-item prop="username">
            <el-input 
              v-model="loginForm.username" 
              placeholder="请输入账号/手机号"
              :prefix-icon="User"
              clearable
              :validate-event="false"
            />
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input 
              v-model="loginForm.password" 
              type="password" 
              placeholder="请输入密码"
              :prefix-icon="Lock"
              :show-password="showPassword"
              :validate-event="false"
            >
              <template #suffix>
                <i 
                  class="el-icon-view" 
                  @click="showPassword = !showPassword"
                  :class="{ 'el-icon-view-close': showPassword }"
                ></i>
              </template>
            </el-input>
          </el-form-item>
          
          <div class="form-options">
            <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
            <el-link type="primary" @click="goToForgotPassword">忘记密码？</el-link>
          </div>
          
          <el-form-item>
            <el-button 
              type="primary" 
              @click="handleLogin"
              :loading="loading"
              class="login-btn"
              :disabled="loading"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>
        
        <!-- 其他登录方式 -->
        <div class="other-login">
          <div class="divider">
            <span class="divider-text">其他登录方式</span>
          </div>
          <div class="third-party-login">
            <el-button 
              type="text" 
              icon="el-icon-weixin" 
              @click="handleThirdPartyLogin('wechat')"
              class="third-party-btn"
            ></el-button>
            <el-button 
              type="text" 
              icon="el-icon-qq" 
              @click="handleThirdPartyLogin('qq')"
              class="third-party-btn"
            ></el-button>
            <el-button 
              type="text" 
              icon="el-icon-alipay" 
              @click="handleThirdPartyLogin('alipay')"
              class="third-party-btn"
            ></el-button>
          </div>
        </div>
        
        <!-- 注册入口 -->
        <div class="register-entry">
          还没有账号？
          <el-link type="primary" @click="goToRegister">立即注册</el-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '../../store/modules/user'
import { User, Lock, ShoppingBag } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 响应式数据
const loginFormRef = ref(null)
const loading = ref(false)
const showPassword = ref(false)
const loginForm = reactive({
  username: '',
  password: '',
  rememberMe: false
})

// 登录表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入账号/手机号', trigger: 'blur' },
    { min: 3, max: 50, message: '账号长度在 3 到 50 个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符之间', trigger: 'blur' }
  ]
}

// 处理登录
const handleLogin = async () => {
  // 表单验证
  try {
    await loginFormRef.value.validate()
  } catch (error) {
    return
  }
  
  loading.value = true
  try {
    // 模拟登录请求
    // 实际项目中应该调用 userStore.login(loginForm.username, loginForm.password, loginForm.rememberMe)
    
    // 模拟登录延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟登录成功
    const mockUserInfo = {
      id: '1',
      username: loginForm.username,
      nickname: 'AI商城用户',
      avatar: '',
      phone: '',
      email: '',
      token: 'mock_token_123456789',
      loginTime: new Date().toISOString()
    }
    
    // 保存用户信息
    userStore.setUserInfo(mockUserInfo)
    userStore.setToken(mockUserInfo.token)
    userStore.setIsLoggedIn(true)
    
    // 如果记住密码，保存到本地存储
    if (loginForm.rememberMe) {
      localStorage.setItem('rememberedUsername', loginForm.username)
    } else {
      localStorage.removeItem('rememberedUsername')
    }
    
    ElMessage.success('登录成功')
    
    // 获取登录前的页面地址，如果没有则跳转到首页
    const redirect = route.query.redirect || '/'
    router.push(redirect)
  } catch (error) {
    ElMessage.error('登录失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 处理第三方登录
const handleThirdPartyLogin = (platform) => {
  ElMessage.info(`即将跳转到${getPlatformName(platform)}授权页面`)
  
  // 实际项目中应该跳转到第三方授权页面
  // 这里仅做演示
  setTimeout(() => {
    // 模拟第三方登录成功
    const mockUserInfo = {
      id: 'third_' + platform + '_123',
      username: platform + '_user',
      nickname: getPlatformName(platform) + '用户',
      avatar: '',
      phone: '',
      email: '',
      token: `mock_${platform}_token_123456789`,
      loginTime: new Date().toISOString()
    }
    
    // 保存用户信息
    userStore.setUserInfo(mockUserInfo)
    userStore.setToken(mockUserInfo.token)
    userStore.setIsLoggedIn(true)
    
    ElMessage.success('登录成功')
    
    // 跳转到首页
    router.push('/')
  }, 1500)
}

// 获取平台名称
const getPlatformName = (platform) => {
  const platformMap = {
    wechat: '微信',
    qq: 'QQ',
    alipay: '支付宝'
  }
  return platformMap[platform] || platform
}

// 跳转到注册页面
const goToRegister = () => {
  router.push('/user/register')
}

// 跳转到忘记密码页面
const goToForgotPassword = () => {
  router.push('/user/forgot-password')
}

// 检查是否有记住的账号
const checkRememberedUsername = () => {
  const rememberedUsername = localStorage.getItem('rememberedUsername')
  if (rememberedUsername) {
    loginForm.username = rememberedUsername
    loginForm.rememberMe = true
  }
}

// 组件挂载时检查记住的账号
checkRememberedUsername()
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: $bg-color;
  background-image: 
    linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

/* 登录卡片 */
.login-card {
  background-color: #fff;
  border-radius: $border-radius-base;
  box-shadow: $shadow-lg;
  width: 100%;
  max-width: 400px;
  padding: 40px;
  box-sizing: border-box;
}

/* 登录头部 */
.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
}

.logo .el-icon {
  font-size: 36px;
  color: $primary-color;
  margin-right: 10px;
}

.logo-text {
  font-size: $font-size-xl;
  color: $primary-color;
  font-weight: bold;
}

.login-title {
  font-size: $font-size-xl;
  color: $text-color;
  font-weight: 500;
  margin-bottom: 10px;
}

.login-subtitle {
  font-size: $font-size-sm;
  color: $text-color-secondary;
  margin: 0;
}

/* 登录表单 */
.login-form {
  width: 100%;
}

.form {
  width: 100%;
}

.form :deep(.el-input) {
  margin-bottom: 20px;
}

.form :deep(.el-input__wrapper) {
  border-radius: $border-radius-base;
  height: 40px;
}

.form :deep(.el-input__inner) {
  border-radius: $border-radius-base;
  height: 40px;
  line-height: 40px;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.form-options :deep(.el-checkbox__label) {
  font-size: $font-size-sm;
  color: $text-color-secondary;
}

.login-btn {
  width: 100%;
  height: 40px;
  font-size: $font-size-base;
  background-color: $primary-color;
  border-color: $primary-color;
}

.login-btn:hover {
  background-color: #409eff;
  border-color: #409eff;
}

/* 其他登录方式 */
.other-login {
  margin-top: 30px;
}

.divider {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.divider::before,
.divider::after {
  content: '';
  flex: 1;
  height: 1px;
  background-color: $border-color;
}

.divider-text {
  padding: 0 10px;
  font-size: $font-size-sm;
  color: $text-color-secondary;
}

.third-party-login {
  display: flex;
  justify-content: center;
  gap: 30px;
}

.third-party-btn {
  font-size: $font-size-xl;
  color: $text-color-secondary;
  transition: color 0.3s;
}

.third-party-btn:hover {
  color: $primary-color;
}

.third-party-btn :deep(.el-icon) {
  font-size: $font-size-xl;
}

/* 注册入口 */
.register-entry {
  text-align: center;
  margin-top: 20px;
  font-size: $font-size-sm;
  color: $text-color-secondary;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-card {
    padding: 30px 20px;
    margin: 20px 0;
  }
  
  .logo .el-icon {
    font-size: 30px;
  }
  
  .logo-text {
    font-size: $font-size-lg;
  }
  
  .login-title {
    font-size: $font-size-lg;
  }
}

@media (max-width: 480px) {
  .login-container {
    padding: 10px;
  }
  
  .login-card {
    padding: 20px 15px;
  }
  
  .third-party-login {
    gap: 20px;
  }
  
  .third-party-btn :deep(.el-icon) {
    font-size: $font-size-lg;
  }
}
</style>